<template>
    <el-card class="question-card" shadow="hover" :body-style="{ padding: '0' }">
      <div class="card-content">
        <!-- 卡片主体内容 -->
        <div class="main-content" @click="handleClick">
          <div class="book-icon" :style="{ backgroundColor: bgColor }">
            <svg width="70" height="90" viewBox="0 0 70 90" fill="none" xmlns="http://www.w3.org/2000/svg">
              <!-- 主体 -->
              <path d="M20 10C20 8.34315 21.3431 7 23 7H110C113.866 7 117 10.134 117 14V166C117 169.866 113.866 173 110 173H23C21.3431 173 20 171.657 20 170V10Z" :fill="bgColor"/>
              <!-- 书脊阴影 -->
              <path d="M20 10C20 8.34315 21.3431 7 23 7H26V173H23C21.3431 173 20 171.657 20 170V10Z" fill="rgba(0,0,0,0.1)"/>
              <!-- 装饰线条 -->
              <rect x="35" y="30" width="70" height="8" rx="2" fill="rgba(0,0,0,0.08)"/>
              <rect x="35" y="50" width="50" height="8" rx="2" fill="rgba(0,0,0,0.08)"/>
              <rect x="35" y="70" width="60" height="8" rx="2" fill="rgba(0,0,0,0.08)"/>
              <!-- 书脊边框 -->
              <path d="M23 7.5H110C113.59 7.5 116.5 10.41 116.5 14V166C116.5 169.59 113.59 172.5 110 172.5H23C21.6193 172.5 20.5 171.381 20.5 170V10C20.5 8.61929 21.6193 7.5 23 7.5Z" stroke="rgba(0,0,0,0.1)" stroke-width="1"/>
            </svg>
          </div>
          <div class="text-content">
            <div class="title">{{ name }}</div>
            <div class="count">{{ count }} 题</div>
          </div>
        </div>

        <!-- 右上角下拉菜单 -->
        <el-dropdown trigger="click" class="dropdown-menu">
          <el-icon class="more-icon"><MoreFilled /></el-icon>
          
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleRename">
                <el-icon><EditPen /></el-icon>重命名
              </el-dropdown-item>
              <el-dropdown-item @click="handleExport" :loading="exporting">
                <el-icon><Download /></el-icon>导出题库
              </el-dropdown-item>
              <el-dropdown-item @click="handleDelete" style="color: red;">
                <el-icon><Delete /></el-icon>删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 重命名对话框 -->
      <el-dialog
        v-model="renameDialogVisible"
        title="重命名题库"
        width="30%"
        :close-on-click-modal="false"
        append-to-body
        destroy-on-close
        :modal-append-to-body="false"
      >
        <el-form :model="renameForm" ref="renameFormRef">
          <el-form-item
            prop="name"
            :rules="[
              { required: true, message: '请输入题库名称', trigger: 'blur' },
              { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
            ]"
          >
            <el-input
              v-model="renameForm.name"
              placeholder="请输入新的题库名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="renameDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmRename">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </template>
  
  <script setup name="QuestionCard">
  import { ref, onMounted } from 'vue'
  import { Document, MoreFilled, EditPen, User, Download, Delete } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { updateLibrary,deleteLibrary} from '@/api/library'
  import { getLibraryQuestions } from '@/api/question'
  // 定义props
  const props = defineProps({
    name: {
      type: String,
      default: '未命名题库'
    },
    subjectId: {
      type: Number,
      default: 0
    },
    subjectName: {
      type: String,
      default: ''
    },
    count: {
      type: Number,
      default: 0
    },
    id: {
      type: Number,
      default: 0
    }
  })

  // 定义emit
  const emit = defineEmits(['refresh'])

  // 定义路由
  const router = useRouter()

  // 导出状态
  const exporting = ref(false)

  // 随机生成柔和的背景颜色
  const generatePastelColor = () => {
    const hue = Math.floor(Math.random() * 360)
    const saturation = 30 + Math.random() * 20
    const lightness = 75 + Math.random() * 15
    return `hsl(${hue}, ${saturation}%, ${lightness}%)`
  }

  const bgColor = ref(generatePastelColor())

  // 重命名相关
  const renameDialogVisible = ref(false)
  const renameFormRef = ref(null)
  const renameForm = ref({
    name: ''
  })

  // 处理重命名
  const handleRename = () => {
    renameForm.value.name = props.name
    renameDialogVisible.value = true
  }

  // 确认重命名
  const confirmRename = async () => {
    if (!renameFormRef.value) return

    await renameFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const response = await updateLibrary(props.id, renameForm.value.name,props.subjectId)
          if (response.code === 200) {
            ElMessage.success('重命名成功')
            renameDialogVisible.value = false
            emit('refresh') // 通知父组件刷新数据
          } else {
            ElMessage.error(response.message || '重命名失败')
          }
        } catch (error) {
          ElMessage.error('操作失败：' + error.message)
        }
      }
    })
  }

  // 处理导出
  const handleExport = async () => {
    const response = await getLibraryQuestions(props.id)
    exportToWord(response.data)
  }

  // 处理删除
  const handleDelete = async () => {
    const response = await deleteLibrary(props.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      emit('refresh') // 通知父组件刷新数据
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  }

  const handleClick =() => {
    router.push({
      path: '/question/detail',
      query: {
        libraryId: props.id,
        libraryName: props.name,
        subjectId: props.subjectId,
        subjectName: props.subjectName
      }
    })
  }


  // 导出Word文档

// 获取题目类型标签样式
const getQuestionTypeTag = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': 'primary',
    'MULTIPLE_CHOICE': 'success',
    'TRUE_FALSE': 'info',
    'FILL_BLANK': 'warning',
    'SHORT_ANSWER': 'danger',
    'READING': 'danger' 
  }
  return typeMap[type] || 'info'
}

// 获取题目类型标签文本
const getQuestionTypeLabel = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': '单选题',
    'MULTIPLE_CHOICE': '多选题',
    'TRUE_FALSE': '判断题',
    'FILL_BLANK': '填空题',
    'SHORT_ANSWER': '简答题',
    'READING': '综合题'
  }
  return typeMap[type] || type
}

// 获取难度标签
const getDifficultyTag = (difficulty) => {
  const difficultyMap = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return difficultyMap[difficulty] || 'info'
}

// 获取难度标签文本
const getDifficultyLabel = (difficulty) => {
  const difficultyMap = {
    1: '简单',
    2: '中等',
    3: '困难'
  }
  return difficultyMap[difficulty] || '未知'
}


const exportToWord = async (Questions) => {
  try {
    exporting.value = true
    
    // 准备导出数据
    const exportData = Questions.map((question, index) => {
      let questionText = `${index + 1} `
      
      // 根据题型添加标题
      switch(question.questionType) {
        case 'SINGLE_CHOICE':
          questionText += '[单选题] '
          break
        case 'MULTIPLE_CHOICE':
          questionText += '[多选题] '
          break
        case 'TRUE_FALSE':
          questionText += '[判断题] '
          break
        case 'FILL_BLANK':
          questionText += '[填空题] '
          break
        case 'SHORT_ANSWER':
          questionText += '[简答题] '
          break
        case 'READING':
          questionText += '[综合题] '
          break
      }
      
      // 根据不同题型处理内容
      if (question.questionType === 'READING') {
        // 综合题题先显示文章内容
        questionText += `\n${question.passage}\n\n`
        
        // 处理子题目
        if (question.subQuestions && question.subQuestions.length > 0) {
          question.subQuestions.forEach((subQ, subIndex) => {
            questionText += `(${subQ.score}分) 第${subIndex + 1}小题：${subQ.stem}\n`
            
            // 如果子题目有选项
            if (subQ.options && subQ.options.length > 0) {
              subQ.options.forEach(option => {
                questionText += `${option.optionId}. ${option.content}\n`
              })
            }
            
            questionText += `答案：${subQ.answer}\n`
            if (subQ.analysis) {
              questionText += `解析：${subQ.analysis}\n`
            }
            questionText += '\n'
          })
        }
      } else if (question.questionType === 'FILL_BLANK') {
        // 填空题处理
        questionText += `${question.stem}\n`
        if (question.blanks) {
          const blanks = question.blanks.split('|')
          blanks.forEach((blank, blankIndex) => {
            questionText += `第${blankIndex + 1}空：${blank}\n`
          })
        }
      } else {
        // 其他题型处理
        questionText += question.stem + '\n'
        
        // 添加选项
        if (question.options && question.options.length > 0) {
          question.options.forEach(option => {
            questionText += `${option.optionId}. ${option.content}\n`
          })
        }
        
        // 添加答案
        questionText += '答案：'
        if (question.questionType === 'SINGLE_CHOICE') {
          questionText += question.answer
        } else if (question.questionType === 'MULTIPLE_CHOICE') {
          questionText += question.answers?.[0] || ''
        } else if (question.questionType === 'TRUE_FALSE') {
          questionText += question.answer === 'TRUE' ? '对' : '错'
        } else {
          questionText += question.answers?.[0] || question.answer || ''
        }
        questionText += '\n'
      }
      
      // 添加难度
      questionText += `难易程度：${getDifficultyLabel(question.difficulty)}\n`
      
      // 添加解析
      if (question.analysis && question.questionType !== 'READING') {
        questionText += `答案解析：${question.analysis}\n`
      }
      
      // 添加知识点
      if (question.knowledgePoints && question.knowledgePoints.length > 0) {
        questionText += `知识点：${question.knowledgePoints.join('；')}\n`
      }
      
      return questionText + '\n'
    }).join('\n')
    
    // 创建Blob对象
    const blob = new Blob([exportData], { type: 'application/msword;charset=utf-8' })
    
    // 创建下载链接
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `${props.name}.doc`
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exporting.value = false
  }
}
  </script>
  
  <style scoped>
  .question-card {
    width: 150px;
    height: 180px;
    background: transparent;
    cursor: pointer;
    transition: transform 0.3s ease;
  }

  .question-card:hover {
    transform: translateY(-5px);
  }
  
  :deep(.el-card) {
    border: none;
    background: transparent;
    box-shadow: none;
  }
  
  .card-content {
    position: relative;
  }
  
  .main-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 12px;
  }
  
  .book-icon {
    width: 70px;
    height: 90px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
  }

  .book-icon:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
  }
  
  .text-content {
    text-align: center;
    width: 100%;
    padding: 0 8px;
  }
  
  .text-content .title {
    font-size: 15px;
    font-weight: 500;
    margin-bottom: 4px;
    color: #333;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .text-content .count {
    font-size: 13px;
    color: #909399;
  }

  .dropdown-menu {
    position: absolute;
    top: 8px;
    right: 8px;
    z-index: 1;
  }
  
  .more-icon {
    padding: 4px;
    cursor: pointer;
    font-size: 18px;
    color: #606266;
    transition: all 0.3s ease;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
  }
  
  .more-icon:hover {
    background-color: #fff;
    color: #409EFF;
  }
  
  :deep(.el-dropdown-menu__item) {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }
  </style>